<template>
  <el-dialog v-model="dialog.visible" :title="dialog.title" width="1200px" append-to-body>
    <el-form ref="foundationInfoFormRef" v-loading="formLoading" :disabled="disabled" :model="formData" :rules="formRules" label-width="100px">
      <div class="kuaicenter">
        <div class="kuai"></div>
        <h2>基础信息</h2>
      </div>
      <el-row :gutter="24">
        <el-col :span="6">
          <el-form-item label="车&nbsp;&nbsp;牌&nbsp;&nbsp;号" prop="form.licensePlateNumber">
            <el-input v-model="formData.form.licensePlateNumber" placeholder="请输入车牌号" />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="车辆类型" prop="form.vehicleType">
            <el-select v-model="formData.form.vehicleType" placeholder="请选择车辆类型">
              <el-option v-for="dict in car_vehicle_type" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="所&nbsp;&nbsp;有&nbsp;&nbsp;人" prop="form.possessor">
            <el-input v-model="formData.form.possessor" placeholder="请输入所有人" />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="租赁状态" prop="form.leaseStatus">
            <el-select
              v-model="formData.form.leaseStatus"
              placeholder="请选择租赁状态"
              :disabled="formType === 'update' && originalLeaseStatus === 'leased'"
            >
              <el-option v-for="dict in car_lease_status" :key="dict.value" :label="dict.label" :value="dict.value" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="动力类型" prop="form.dynamicType">
            <el-select v-model="formData.form.dynamicType" placeholder="请选择动力类型">
              <el-option v-for="dict in car_dynamic_type" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="车辆品牌" prop="form.vehicleBrand">
            <el-input v-model="formData.form.vehicleBrand" placeholder="请输入车辆品牌" />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="车辆颜色" prop="form.vehicleColor">
            <el-input v-model="formData.form.vehicleColor" placeholder="请输入车辆颜色" />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="型号" prop="form.modeNumber">
            <el-input v-model="formData.form.modeNumber" placeholder="请输入型号" />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="识别代码" prop="form.identificationCode">
            <el-input v-model="formData.form.identificationCode" placeholder="请输入识别代码" />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="注册日期" prop="form.registration">
            <el-date-picker clearable v-model="formData.form.registration" type="date" value-format="YYYY-MM-DD" placeholder="请选择注册日期">
            </el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="下次年审日期" prop="form.nextAnnualInspectionDate">
            <el-date-picker clearable v-model="formData.form.nextAnnualInspectionDate" type="date" value-format="YYYY-MM-DD" placeholder="请选择下次年审日期">
            </el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="车险提醒日期" prop="form.insuranceReminderDate">
            <el-date-picker clearable v-model="formData.form.insuranceReminderDate" type="date" value-format="YYYY-MM-DD" placeholder="请选择车险提醒日期">
            </el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="核定载人数" prop="form.authorizedCapacity">
            <el-input v-model="formData.form.authorizedCapacity" placeholder="请输入核定载人数" />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="购买金额" prop="form.purchaseAmount">
            <el-input v-model="formData.form.purchaseAmount" placeholder="请输入购买金额" />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="车辆估值" prop="form.vehicleValuation">
            <el-input v-model="formData.form.vehicleValuation" placeholder="请输入车辆估值" />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="车辆照片" prop="form.vehicleImages">
            <el-upload
              v-model:file-list="formData.form.vehicleImages"
              action="/dev-api/common/upload"
              list-type="picture-card"
              :on-preview="handlePictureCardPreview"
              :on-remove="handleRemove"
              :on-success="handleUploadSuccess"
              :before-upload="beforeUpload"
              multiple
            >
              <el-icon><Plus /></el-icon>
            </el-upload>
            <el-dialog v-model="previewVisible" title="图片预览">
              <img w-full :src="previewUrl" alt="车辆照片预览" />
            </el-dialog>
          </el-form-item>
        </el-col>
      </el-row>
      <div v-if="formData.form.leaseStatus !== 'leased' && formType != 'history'" style="margin: 32px 0">
        <el-empty description="请将租赁状态修改为已租赁以添加租赁信息和收租计划" />
      </div>
      <div v-if="formData.form.leaseStatus === 'leased' || formType == 'history'">
        <div class="kuaicenter">
          <div class="kuai"></div>
          <h2>租赁信息</h2>
        </div>
        <el-row :gutter="24" style="position: reactive">
          <div style="font-size: 10px; color: #7f7f90; position: absolute; top: 96px; right: 0">
            注意：选择退租后，基础信息中的车辆状态变为闲置中，租赁信息及收租计划将清空，您可在历史租赁信息查看！
          </div>
          <el-col :span="6" class="mb-2">
            <el-form-item label="承租人" prop="carRentalInfoForm.name">
              <el-input v-model="formData.carRentalInfoForm.name" placeholder="请输入承租人" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="联系人" prop="carRentalInfoForm.associate">
              <el-input v-model="formData.carRentalInfoForm.associate" placeholder="请输入联系人" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="联系方式" prop="carRentalInfoForm.contactInformation">
              <el-input v-model="formData.carRentalInfoForm.contactInformation" placeholder="请输入联系方式" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="缴租频次" prop="carRentalInfoForm.frentPaymentFrequency">
              <el-select v-model="formData.carRentalInfoForm.frentPaymentFrequency" placeholder="请选择缴租频次">
                <el-option v-for="dict in park_frent_payment_frequency" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6" class="mb-2">
            <el-form-item label="开始时间" prop="carRentalInfoForm.startTime">
              <el-date-picker
                clearable
                v-model="formData.carRentalInfoForm.startTime"
                type="date"
                value-format="YYYY-MM-DD"
                placeholder="请选择开始时间"
              >
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="结束时间" prop="carRentalInfoForm.endTime">
              <el-date-picker
                clearable
                v-model="formData.carRentalInfoForm.endTime"
                type="date"
                value-format="YYYY-MM-DD"
                placeholder="请选择结束时间"
              >
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="退租类型" prop="rentOutStatus">
              <el-select v-model="formData.carRentalInfoForm.rentOutStatus" placeholder="请选择退租类型">
                <el-option v-for="dict in park_surrender_tenancy_status" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="退租时间" prop="rentOutTime">
              <el-date-picker
                clearable
                v-model="formData.carRentalInfoForm.rentOutTime"
                type="date"
                value-format="YYYY-MM-DD"
                placeholder="请选择退租时间"
              >
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="租赁总额" prop="carRentalInfoForm.totalLease">
              <el-input v-model="formData.carRentalInfoForm.totalLease" placeholder="请输入租赁总额" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="已收金额" prop="carRentalInfoForm.amountReceived">
              <el-input v-model="formData.carRentalInfoForm.amountReceived" placeholder="请输入已收金额" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="欠款金额" prop="carRentalInfoForm.amountDue">
              <el-input v-model="formData.carRentalInfoForm.amountDue" placeholder="请输入欠款金额" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="折合日租金" prop="carRentalInfoForm.equivalentDailyRent">
              <el-input v-model="formData.carRentalInfoForm.equivalentDailyRent" placeholder="请输入折合日租金" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="处理状态" prop="carRentalInfoForm.processingStatus">
              <el-select v-model="formData.carRentalInfoForm.processingStatus" placeholder="请选择处理状态">
                <!-- 选项内容将从接口获取 -->
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="违章记录" prop="carRentalInfoForm.violationRecord">
              <el-input 
                v-model="formData.carRentalInfoForm.violationRecord" 
                type="textarea" 
                :rows="3" 
                placeholder="请输入违章记录详情" 
              />
            </el-form-item>
          </el-col>
        </el-row>
      </div>
      <div v-if="formData.form.leaseStatus === 'leased' || formType == 'history'">
        <div class="kuaicenter">
          <div class="kuai"></div>
          <h2 class="text-black">收租计划</h2>
        </div>
        <div v-if="formData.rentCollectionPlan.length === 0" style="text-align: right">
          <el-button :loading="buttonLoading" type="primary" @click="handlePush">辅助生成</el-button>
        </div>
        <H2 class="mb-5" style="text-align: center; font-weight: bold">收租计划</H2>
        <el-table :data="formData.rentCollectionPlan" style="width: 100%" :show-summary="true" :summary-method="getSummaries">
          <el-table-column type="index" label="序号" width="60" />
          <el-table-column prop="dueDate" label="应收日期">
            <template #default="scope">
              <el-date-picker v-model="scope.row.dueDate" value-format="YYYY-MM-DD" type="date" />
            </template>
          </el-table-column>
          <el-table-column prop="rentReceivable" label="应收租金(元)">
            <template #default="scope">
              <el-input v-model="scope.row.rentReceivable" class="cell-input" />
            </template>
          </el-table-column>
          <el-table-column prop="collect" label="是否收取" width="160">
            <template #default="scope">
              <el-radio-group v-model="scope.row.collect">
                <el-radio :value="false" size="large">否</el-radio>
                <el-radio :value="true" size="large">是</el-radio>
              </el-radio-group>
            </template>
          </el-table-column>
          <el-table-column prop="paidInTime" label="实收日期">
            <template #default="scope">
              <el-date-picker v-model="scope.row.paidInTime" value-format="YYYY-MM-DD" type="date" />
            </template>
          </el-table-column>
          <el-table-column width="110" label="操作" align="center" class-name="small-padding fixed-width">
            <template #default="scope">
              <div v-if="disabled">-</div>
              <div v-else>
                <el-button link type="primary" @click="handleAdd(scope.$index)">新增</el-button>
                <el-button link type="danger" @click="handleDelete(scope.$index, scope.row)">删除</el-button>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-form>
    <template v-if="!disabled" #footer>
      <div class="dialog-footer">
        <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="dialog.visible = false">取 消</el-button>
      </div>
    </template>
  </el-dialog>
</template>
<script lang="ts" name="SystemRoleForm" setup>
import {
  listCarbasicInformation,
  getCarbasicInformation,
  delCarbasicInformation,
  addCarbasicInformation,
  updateCarbasicInformation,
  addCarRentalProgram,
  updateCarRentalProgram,
  getCarRentalProgram,
  delCarRentalProgram
} from '@/api/zichanguanli/carbasicInformation/index';
import { validateNumber, validateInteger } from '@/utils/formRules';
import { getCarrentalInfo, addCarrentalInfo, updateCarrentalInfo } from '@/api/zichanguanli/carrentalInfo/index';
import { getLeaseInformation, addLeaseInformation, updateLeaseInformation } from '@/api/zichanguanli/leaseInformation';
import { fa } from 'element-plus/es/locale/index.mjs';
import dayjs from 'dayjs';
import { generateRentPlan, generateSingleRentPlan } from '@/utils/genRentProject';
import { Plus } from '@element-plus/icons-vue';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { car_vehicle_type, car_dynamic_type, car_lease_status, park_surrender_tenancy_status, park_frent_payment_frequency } = toRefs<any>(
  proxy?.useDict('car_vehicle_type', 'car_dynamic_type', 'car_lease_status', 'park_surrender_tenancy_status', 'park_frent_payment_frequency')
);

// 表单字段配置
const formFields = [
  { label: '园区名称', prop: 'form.name', model: 'name', type: 'text' },
  { label: '位置', prop: 'form.position', model: 'position', type: 'text' },
  { label: '面积(亩)', prop: 'form.area', model: 'area', type: 'text' },
  { label: '建筑面积', prop: 'form.floorArea', model: 'floorArea', type: 'text' },
  { label: '管理单位', prop: 'form.managementUnit', model: 'managementUnit', type: 'text' },
  { label: '对接人', prop: 'form.contactPerson', model: 'contactPerson', type: 'text' },
  { label: '联系人', prop: 'form.associates', model: 'associates', type: 'text' },
  { label: '园区估值', prop: 'form.estimation', model: 'estimation', type: 'text' },
  { label: '物业公司', prop: 'form.propertyCompany', model: 'propertyCompany', type: 'text' },
  { label: '物业人数', prop: 'form.numberOfProperties', model: 'numberOfProperties', type: 'text' },
  { label: '物业联系人', prop: 'form.propertyContacts', model: 'propertyContacts', type: 'text' },
  { label: '物业电话', prop: 'form.propertyTelephone', model: 'propertyTelephone', type: 'text' },
  { label: '园区备注', prop: 'form.remark', model: 'remark', type: 'text' },
  { label: '园区介绍', prop: 'form.introduce', model: 'introduce', type: 'text' },
  { label: '园区附件', prop: 'form.attachments', model: 'attachments', type: 'file' },
  { label: '实景图片', prop: 'form.images', model: 'images', type: 'image' }
];

const formRules = reactive({
  'form.licensePlateNumber': [
    { required: true, message: '车牌号不能为空', trigger: 'blur' },
    {
      pattern: /^[京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领][A-HJ-NP-Z][A-HJ-NP-Z0-9]{4,5}[A-HJ-NP-Z0-9挂学警港澳]$/,
      message: '请填写正确的车牌号',
      trigger: 'change'
    }
  ],
  'form.propertyTelephone': [{  required: true, message: '请填写正确的手机号码', trigger: 'change' }],
  'form.vehicleType': [{ required: true, message: '车辆类型不能为空', trigger: 'change' }],
  'form.possessor': [{ required: true, message: '所有人不能为空', trigger: 'blur' }],
  'form.leaseStatus': [{ required: true, message: '租赁状态不能为空', trigger: 'change' }],
  'form.dynamicType': [{ required: true, message: '动力类型不能为空', trigger: 'change' }],
  'form.vehicleBrand': [{ required: true, message: '车辆品牌不能为空', trigger: 'blur' }],
  'form.authorizedCapacity': [{ validator: validateInteger, trigger: ['change', 'blur'] }],
  'form.purchaseAmount': [{ validator: validateNumber, trigger: ['change', 'blur'] }],
  'form.vehicleValuation': [{ validator: validateNumber, trigger: ['change', 'blur'] }],
  'carRentalInfoForm.equivalentDailyRent': [{ validator: validateNumber, trigger: ['change', 'blur'] }],
  'carRentalInfoForm.name': [{ required: true, message: '承租人不能为空', trigger: 'blur' }],
  'carRentalInfoForm.associate': [{ required: true, message: '联系人不能为空', trigger: 'blur' }],
  'carRentalInfoForm.contactInformation': [
    { required: true, message: '联系方式不能为空', trigger: 'blur' },
    {  required: true, message: '请填写正确的手机号码', trigger: 'change' }
  ],
  'carRentalInfoForm.frentPaymentFrequency': [{ required: true, message: '缴租频次不能为空', trigger: 'change' }],
  'carRentalInfoForm.startTime': [{ required: true, message: '开始时间不能为空', trigger: 'change' }],
  'carRentalInfoForm.endTime': [{ required: true, message: '结束时间不能为空', trigger: 'change' }],
  'carRentalInfoForm.totalLease': [
    { required: true, message: '租赁总额不能为空', trigger: 'blur' },
    { validator: validateNumber, trigger: ['change', 'blur'] }
  ],
  'carRentalInfoForm.amountReceived': [{ validator: validateNumber, trigger: ['change', 'blur'] }],
  'carRentalInfoForm.amountDue': [{ validator: validateNumber, trigger: ['change', 'blur'] }]
});

const disabled: any = ref(false); // 表单是否禁用
const buttonLoading = ref(false); // 按钮的 loading
const dialog = reactive({
  visible: false,
  title: ''
});
const formLoading = ref(false); // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref(''); // 表单的类型：create - 新增；update - 修改

const formData: any = ref({
  form: {
    licensePlateNumber: undefined,
    vehicleType: undefined,
    possessor: undefined,
    leaseStatus: 'in_idle',
    dynamicType: 'other',
    vehicleBrand: undefined,
    vehicleColor: undefined,
    modeNumber: undefined,
    identificationCode: undefined,
    registration: undefined,
    nextAnnualInspectionDate: undefined,
    insuranceReminderDate: undefined,
    authorizedCapacity: undefined,
    purchaseAmount: undefined,
    vehicleValuation: undefined,
    vehicleImages: []
  },
  carRentalInfoForm: {
    name: undefined,
    associate: undefined,
    contactInformation: undefined,
    frentPaymentFrequency: undefined,
    startTime: undefined,
    endTime: undefined,
    rentOutTime: undefined,
    rentOutStatus: undefined,
    totalLease: undefined,
    amountReceived: undefined,
    amountDue: undefined,
    equivalentDailyRent: undefined,
    processingStatus: undefined,
    violationRecord: undefined
  },
  rentCollectionPlan: []
});
const foundationInfoFormRef = ref(); // 表单 Ref

const originalLeaseStatus = ref('');

const previewVisible = ref(false);
const previewUrl = ref('');

const handlePictureCardPreview = (file: any) => {
  previewUrl.value = file.url || file.response.url;
  previewVisible.value = true;
};

const handleRemove = (file: any, fileList: any) => {
  formData.value.form.vehicleImages = fileList;
};

const handleUploadSuccess = (response: any, file: any, fileList: any) => {
  formData.value.form.vehicleImages = fileList;
  if (response.code === 200) {
    file.url = response.data.url;
    file.name = response.data.fileName;
  }
};

const beforeUpload = (file: any) => {
  const isImage = file.type.startsWith('image/');
  const isLt2M = file.size / 1024 / 1024 < 5;

  if (!isImage) {
    ElMessage.error('只能上传图片格式文件!');
    return false;
  }
  if (!isLt2M) {
    ElMessage.error('图片大小不能超过 5MB!');
    return false;
  }
  return true;
};

const handlePush = () => {
  if (
    !formData.value.carRentalInfoForm.name ||
    !formData.value.carRentalInfoForm.frentPaymentFrequency ||
    !formData.value.carRentalInfoForm.startTime ||
    !formData.value.carRentalInfoForm.endTime ||
    !formData.value.carRentalInfoForm.totalLease
  ) {
    ElMessage.error('请填写完整的租赁信息');
    return;
  }

  const startDate = dayjs(formData.value.carRentalInfoForm.startTime);
  const endDate = dayjs(formData.value.carRentalInfoForm.endTime);

  const frequencyMap = {
    'monthly_payment': 1,
    'quarterly_contributions': 3,
    'semi_annual_contributions': 6,
    'year_payment': 12
  };

  const monthDiff = endDate.diff(startDate, 'month');
  const frequency = frequencyMap[formData.value.carRentalInfoForm.frentPaymentFrequency];
  const periods = Math.ceil(monthDiff / frequency);

  const rentPerPeriod = Number((formData.value.carRentalInfoForm.totalLease / periods).toFixed(2));

  const plans = generateRentPlan({
    frequencyOfRentPayments: formData.value.carRentalInfoForm.frentPaymentFrequency,
    rents: rentPerPeriod,
    startTime: formData.value.carRentalInfoForm.startTime,
    endTime: formData.value.carRentalInfoForm.endTime,
    transform: false
  });

  formData.value.rentCollectionPlan = plans;
};

const handleDelete = async (index: number, row: any) => {
  if (row.id) {
    await delCarRentalProgram(row.id);
    formData.value.rentCollectionPlan.splice(index, 1);
  } else {
    formData.value.rentCollectionPlan.splice(index, 1);
  }
};

const handleAdd = (index: number) => {
  const newPlan = generateSingleRentPlan();
  formData.value.rentCollectionPlan.splice(index + 1, 0, newPlan);
};

/** 打开弹窗 */
const open = async (type: string, carRentalInfoId?: number | string, automobileBasicInfoId?: number | string) => {
  dialog.visible = true;
  formType.value = type;
  disabled.value = false;
  resetForm();

  if (type === 'detail' || type === 'history') {
    disabled.value = true;
  }

  if (automobileBasicInfoId) {
    formLoading.value = true;
    try {
      const params = {
        automobileBasicInfoId,
        carRentalInfoId: carRentalInfoId
      };
      const res = await getCarbasicInformation(params);
      const datas = res.data;
      formData.value.form = datas.automobileBasicInformationVo;
      formData.value.carRentalInfoForm = datas.carRentalInfoVo || {};
      formData.value.rentCollectionPlan = datas.carRentalProgramVo || [];

      originalLeaseStatus.value = datas.automobileBasicInformationVo.leaseStatus;
    } finally {
      formLoading.value = false;
    }
  }
};

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    form: {
      licensePlateNumber: undefined,
      vehicleType: undefined,
      possessor: undefined,
      leaseStatus: 'in_idle',
      dynamicType: 'other',
      vehicleBrand: undefined,
      vehicleColor: undefined,
      modeNumber: undefined,
      identificationCode: undefined,
      registration: undefined,
      nextAnnualInspectionDate: undefined,
      insuranceReminderDate: undefined,
      authorizedCapacity: undefined,
      purchaseAmount: undefined,
      vehicleValuation: undefined,
      vehicleImages: []
    },
    carRentalInfoForm: {
      name: undefined,
      associate: undefined,
      contactInformation: undefined,
      frentPaymentFrequency: undefined,
      startTime: undefined,
      endTime: undefined,
      rentOutTime: undefined,
      rentOutStatus: undefined,
      totalLease: undefined,
      amountReceived: undefined,
      amountDue: undefined,
      equivalentDailyRent: undefined,
      processingStatus: undefined,
      violationRecord: undefined
    },
    rentCollectionPlan: []
  };
  originalLeaseStatus.value = '';
  foundationInfoFormRef.value?.resetFields();
};
defineExpose({ open }); // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success', 'getList']); // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  const valid = await foundationInfoFormRef.value.validate();
  if (!valid) return;
  // 提交请求
  formLoading.value = true;
  try {
    let type = '';
    if (formType.value === 'create') {
      const datas = {
        automobileBasicInformationBo: formData.value.form,
        carRentalInfoBo: formData.value.carRentalInfoForm,
        carRentalProgramBos: formData.value.rentCollectionPlan
      };
      await addCarbasicInformation(datas);
    } else {
      type = 'update';
      const datas = {
        automobileBasicInformationBo: formData.value.form,
        carRentalInfoBo: formData.value.carRentalInfoForm,
        carRentalProgramBos: formData.value.rentCollectionPlan
      };
      await updateCarbasicInformation(datas);
    }
    dialog.visible = false;
    emit('getList');
    // 发送操作成功的事件
    emit('success', type);
  } finally {
    formLoading.value = false;
  }
};

const calculateTotal = (field: string) => {
  return formData.value.rentCollectionPlan
    .reduce((sum: number, item: any) => {
      return sum + (Number(item[field]) || 0);
    }, 0)
    .toFixed(2);
};

// 添加合计方法
const getSummaries = (param: any) => {
  const { columns, data } = param;
  const sums: any[] = [];
  columns.forEach((column: any, index: number) => {
    if (index === 0) {
      sums[index] = '合计';
      return;
    }
    if (index === 2) {
      // 应收租金列的索引
      const values = data.map((item: any) => Number(item.rentReceivable) || 0);
      sums[index] = values.reduce((prev: number, curr: number) => {
        return prev + curr;
      }, 0);
      // 格式化数字，保留2位小数
      sums[index] = sums[index].toFixed(2);
    } else {
      sums[index] = '';
    }
  });
  return sums;
};

// 监听租赁状态的变化
watch(
  () => formData.value.form.leaseStatus,
  (newValue) => {
    if (newValue !== 'leased' && formType.value != 'history' && formType.value != 'detail') {
      // 如果切换到非已出租状态，清空租赁信息和收租计划
      formData.value.carRentalInfoForm = {
        name: undefined,
        associate: undefined,
        contactInformation: undefined,
        frentPaymentFrequency: undefined,
        startTime: undefined,
        endTime: undefined,
        rentOutTime: undefined,
        rentOutStatus: undefined,
        totalLease: undefined,
        amountReceived: undefined,
        amountDue: undefined,
        equivalentDailyRent: undefined,
        processingStatus: undefined,
        violationRecord: undefined
      };
      formData.value.rentCollectionPlan = [];
    }
    if (newValue === 'leased' && formType.value != 'history' && formType.value != 'detail') {
      // 当租赁状态为已租赁时，设置退租状态为在租
      formData.value.carRentalInfoForm.rentOutStatus = 'under_rent';
    }
  }
);
</script>

<style>
.mb-5 {
  margin-bottom: 20px;
}
</style>
